package com.spica.spicaschool.ui.circle

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.drakeet.multitype.MultiTypeAdapter
import com.fondesa.recyclerviewdivider.dividerBuilder
import com.spica.spicaschool.base.ILoadMoreAdapter
import com.spica.spicaschool.base.LoadMoreAdapterWrapper
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.bean.diary.Diary
import com.spica.spicaschool.utils.SpUtils
import com.spica.spicaschool.utils.TOKEN_SIGN
import com.spica.spicaschool.utils.UiUtils
import com.spica.spicaschool.view.ListLayout
import com.spica.spicaschool.viewmodel.CircleViewModel
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber

/**
 * 动态列表
 */

private const val TYPE_SIGN = "type"

@AndroidEntryPoint
class DiariesFragment : Fragment(), ILoadMoreAdapter,
  LoadMoreAdapterWrapper.OnClickRetryListener {

  private val page = PageEntity()

  private var type = 1

  private val items = mutableListOf<Diary>()

  private lateinit var adapter: MultiTypeAdapter

  private val viewModel: CircleViewModel by viewModels()

  private var isOk = false // 是否完成View初始化

  private var isFirst = true // 是否为第一次加载

  private var isError = false

  private var isLoading = false

  private lateinit var listLayout: ListLayout


  companion object {
    // 传入参数
    fun newInstance(type: Int = 1): Fragment {
      val fragment = DiariesFragment()
      val bundle = Bundle()
      bundle.putInt(TYPE_SIGN, type)
      fragment.arguments = bundle
      return fragment
    }
  }


  override fun onResume() {
    super.onResume()
    initLoadData()
  }

  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
  ): View {
    listLayout = ListLayout(requireContext())
    return listLayout
  }


  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    init()
  }


  private fun init() {
    // 获取传入类型
    val bundle = arguments
    if (bundle != null) type = bundle.getInt(TYPE_SIGN)
    initData()
  }

  private fun initData() {
    // 初始化适配器
    adapter = MultiTypeAdapter()
    // 多类型列表注册多适配器
    adapter.register(Diary::class).to(DiaryItemDelegate(requireActivity()))
      .withKotlinClassLinker { _, item ->
        when (item.diaryType) {
          1 -> DiaryItemDelegate::class
          else -> DiaryItemDelegate::class
        }
      }
    // 获取数据源
    adapter.items = items
    adapter.setHasStableIds(true) // 做diff
    listLayout.recyclerView.adapter = LoadMoreAdapterWrapper(
      requireContext(),
      adapter, this,
      this
    )

    //设置分割线
    requireContext()
      .dividerBuilder()
      .size(8, TypedValue.COMPLEX_UNIT_DIP)
      .asSpace()
      .showLastDivider()
      .showFirstDivider()
      .build()
      .addTo(listLayout.recyclerView)


    listLayout.swipeRefreshLayout.setOnRefreshListener {
      onLoadData(isRefresh = true)
    }
    isOk = true
  }


  @SuppressLint("NotifyDataSetChanged")
  private fun initLoadData() {
    if (isOk && isFirst) {
      viewModel.fetchDiaryList(
        type = 1,
        onError = {
          isError = true
          Timber.e("请求过程发生错误：$it")
        },
        onComplete = {
          isLoading = false
          Timber.e("请求结束")
        },
        onStart = {
          isLoading = true
          Timber.e("请求开始")
        },
        token = SpUtils.getSpValue(
          context = requireContext(),
          key = TOKEN_SIGN,
          defaultVal = ""
        )
      )
      //初始化数据监听
      viewModel.diaryListLiveData.observe(this) {
        page.nextPage = it.pageInfo.nextPage
        items.addAll(it.data)
        UiUtils.doMainThreadle({
          listLayout.swipeRefreshLayout.isRefreshing = false
        })
        adapter.notifyDataSetChanged()
      }
      // 加载数据时判断是否完成view的初始化，以及是不是第一次加载此数据
      onLoadData(true)
      isFirst = false // 加载第一次数据后改变状态，后续不再重复加载
    }
  }

  /**
   * 加载数据
   * isRefresh：是否刷新
   **/
  @SuppressLint("NotifyDataSetChanged")
  private fun onLoadData(isRefresh: Boolean) {
    if (isRefresh) {
      isError = false
      items.clear()
      page.currentPage = 1
    }
    viewModel.pageChanged(PageEntity(currentPage = page.currentPage++))
  }

  // 加载更多
  private fun onLoadMore() {
    if (!page.nextPage) return else
      onLoadData(false)
  }


  override fun hasMoreResults(): Boolean {
    return page.nextPage
  }

  override fun hasError(): Boolean {
    return isError
  }

  override fun isLoading(): Boolean {
    if (!isLoading) {
      listLayout.swipeRefreshLayout.isRefreshing = false
    }
    return isLoading
  }

  //点击加载更多
  override fun onClickRetry() {
    Timber.e("加载更多...")
    onLoadMore()
  }
}